/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout from '@ant-design/pro-layout';
import { useEffect, useState } from 'react';
import Link from 'umi/link';
import { connect } from 'dva';
import { formatMessage } from 'umi-plugin-react/locale';
import { Menu, Row, Col, Button, Icon } from 'antd';
import RightContent from '@/components/GlobalHeader/RightContent';
import Authorized from '@/utils/Authorized';
// import { isAntDesignPro } from '@/utils/utils';
// import logo from '../assets/logo.svg';
import logo from '../../public/img/logo.png';
import { axhttp } from '@/utils/axhttp';
import { axurl } from '@/shared/axurl';
import styles from './BasicLayout.less'; //不能去掉
import { axconst } from '@/shared/axconst';
import { router } from 'umi';
import { axhelper } from '@/shared/axhelper';

const { SubMenu } = Menu;
const footerRender = name => (
  // if (!isAntDesignPro()) {
  //   return defaultDom;
  // }

  <>
    {/* {defaultDom} */}
    <div
      style={{
        padding: '0px 24px 24px',
        textAlign: 'center',
        backgroundColor: 'rgb(240,242,245)',
      }}
    >
      <div>Copyright ©2020 {name}</div>
      {/* <a href="https://www.netlify.com" target="_blank" rel="noopener noreferrer">
          <img
            src="https://www.netlify.com/img/global/badges/netlify-color-bg.svg"
            width="82px"
            alt="netlify logo"
          />
        </a> */}
    </div>
  </>
);
const BasicLayout = props => {
  const { dispatch, children, collapsed, settings, currentApp, clientWidth } = props;
  const [menuData, setMenuData] = useState([]);
  const [headerMenu, setHeaderMenu] = useState([]);
  const [defaultSelectedKeys, setDefaultSelectedKeys] = useState([]);
  const [collapseIcon, setCollapseIcon] = useState('menu-fold');
  const [openKeys, setOpenKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);

  const handleClientWidth = () => {
    const { dispatch } = props;
    return dispatch({
      type: `global/readClientWidth`,
      params: {
        clientWidth: window.document.body.clientWidth,
      },
    });
  };

  useEffect(() => {
    async function fetchData() {
      const res = await axhttp.getXhr('/api/menu/readx');
      if (res && res.success === true) {
        const data = res.data;
        // localStorage.setItem('ax-data-menu', JSON.stringify(data));
        handleMenu(data);
      }
    }
    fetchData();

    axhelper.getDictionary();
  }, []);

  const handleMenu = data => {
    const transformData = [];
    if (data && data.length > 0) {
      data.forEach(i => {
        transformData.push(transFormMenus(i));
      });
      setHeaderMenu(transformData);

      if (transformData.length > 0) {
        let { hash } = location;
        if (hash.length > 0) {
          hash = hash.substring(1);
        }
        let find = transformData.find(i => {
          /** 精确匹配 */
          const h = /\/(\S+?)\//.exec(hash);
          if (h && h.length > 0 && i.path + '/' === h[0]) return true;
          return false;
        });
        // setMenuData([...transformData]);
        // return;
        /** 模糊匹配 */
        if (find === undefined) find = transformData.find(i => hash.indexOf(i.path) !== -1);
        if (find) {
          // setMenuData(find.children || []);
          setMenuData([...transformData]);
          setDefaultSelectedKeys([find.id]);
        } else {
          // setMenuData(transformData[0].children || []);
          setMenuData([...transformData]);
          setDefaultSelectedKeys([transformData[0].id]);
        }
      }
    }
  };

  /** 转换菜单格式 */
  const transFormMenus = menu => {
    let obj = {};
    if (menu.children && menu.children.length > 0) {
      const menuChildren = [];
      menu.children.forEach(i => {
        menuChildren.push(transFormMenus(i));
      });
      obj = {
        id: menu.id,
        // key: menu.id,    //这里不能用key，默认将url作为了key，否则菜单展示会有问题
        path: menu.url,
        name: menu.text,
        icon: menu.iconCls,
        // icon: (menu.deep === 1 || menu.deep === 2) ? menu.iconCls : undefined,
        // hideInMenu: true,  //不展示改菜单
        // hideChildrenInMenu: true,  //不展示改菜单的子菜单
        // authority: ['admin', 'user'], //代表该路由的准入权限
        children: menuChildren,
        permissions: menu.permissions,
      };
    } else {
      obj = {
        id: menu.id,
        // key: menu.id,
        path: menu.url,
        name: menu.text,
        icon: menu.iconCls,
        // icon: (menu.deep === 1 || menu.deep === 2) ? menu.iconCls : undefined,
        permissions: menu.permissions,
        // hideInMenu: true,  //不展示改菜单
        // hideChildrenInMenu: true,  //不展示改菜单的子菜单
        // icon: menu.iconCls
      };
    }
    return obj;
  };

  /** 菜单折叠操作函数 */
  const handleMenuCollapse = payload => {
    setCollapseIcon(payload === false ? 'menu-fold' : 'menu-unfold');
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  };

  /** 顶部菜单点击操作函数 */
  const handleHeaderMenu = ({ key }) => {
    if (headerMenu) {
      const menu = headerMenu.find(i => i.id === key);
      menu && router.push(menu.path);
    }
  };

  const getPathFromMenus = (k, m) => {
    for (let i = 0; i < m.length; i++) {
      const menu = m[i];
      if (menu.id === k) {
        return menu.path;
      } else {
        if (menu.children) {
          const path = getPathFromMenus(k, menu.children);
          if (path) {
            return path;
          }
        }
      }
    }
  };

  const genMenus = menus => {
    return menus.map(i => {
      if (i.children) {
        return (
          <SubMenu
            key={i.id}
            onClick={({ key }) => {
              const path = getPathFromMenus(key, headerMenu);
              path && router.push(path);
            }}
            title={
              <span>
                {i.icon && <Icon type={i.icon} />}
                {i.name}
              </span>
            }
          >
            {genMenus(i.children)}
          </SubMenu>
        );
      } else {
        return (
          <Menu.Item key={i.id}>
            {i.icon && <Icon type={i.icon} />}
            {i.name}
          </Menu.Item>
        );
      }
    });
  };

  return (
    <ProLayout
      contentStyle={{ margin: 0 }}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.isUrl) {
          return defaultDom;
        }
        return (
          <Link to={menuItemProps.path} replace>
            {defaultDom}
          </Link>
        );
      }}
      breadcrumbRender={(routers = []) => [
        {
          path: '/',
          breadcrumbName: formatMessage({
            id: 'menu.home',
            defaultMessage: 'Home',
          }),
        },
        ...routers,
      ]}
      itemRender={(route, params, routes, paths) => {
        const first = routes.indexOf(route) === 0;
        return first ? (
          <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
        ) : (
          <span>{route.breadcrumbName}</span>
        );
      }}
      headerRender={() => (
        <>
          <a style={{ paddingLeft: 16 }}>
            {/* <img src="/img/logo.png" style={{ height: 44, marginBottom: 2 }} /> */}
            商城购物平台
          </a>
          <RightContent style={{ float: 'right', width: 98 }}></RightContent>
          <Menu
            theme="light"
            mode="horizontal"
            selectedKeys={defaultSelectedKeys}
            style={{
              lineHeight: `${axconst.header.height - 2}px`,
              float: 'right',
              backgroundColor: '#409eff',
            }}
            onClick={({ key }) => handleHeaderMenu({ key })}
          >
            {(menuData && menuData.length > 0 && genMenus(menuData)) || <></>}
          </Menu>
        </>
      )}
      footerRender={() => footerRender(currentApp.orgName)}
      menuDataRender={() => menuData}
      {...props}
      {...settings}
      title={currentApp.appName}
      collapsed={true}
    >
      {children}
    </ProLayout>
  );
};

export default connect(({ global, settings, user }) => ({
  collapsed: global.collapsed,
  clientWidth: global.clientWidth,
  settings,
  currentApp: user.currentApp,
}))(BasicLayout);
